package mammuthus.web.service

import net.csdn.common.path.Url

/**
 * 6/15/15 WilliamZhu(allwefantasy@gmail.com)
 */
trait AppConfigure {
  this: SlaveService =>


  def deploy(params: Map[String, String]) = {
    val app = params("app")
    val appName = params("appName")
    val version = params("version")
    val _url = params.getOrElse("_url", "")
    val slave = params("slave")
    val url = if (_url.endsWith(".git")) _url else s"${masterUrl}/${app}@${version}.tar.gz"

    val installUrl = new Url(s"${masterUrl}/app/install?${authTokenStr}").
      addParam("slaves", encode(s"${slave}")).
      addParam("appVersion", encode(version)).
      addParam("url", encode(url)).
      addParam("filePath", encode(s"${softwareDir}/${app}@${version}.tar.gz")).
      addParam("installPath", encode(applicationDir)).
      addParam("appName", encode(appName)).
      addParam("app", encode(app)).
      addParam("tt", encode("1800000")
      )
    logger.info("install deploy {}", installUrl.toString)
    val rps = httpClient.get(installUrl)
    generateShellResult(rps, 60)
  }

  def config(params: Map[String, String], user: String) = {

    val appName = params("appName")
    val version = params("version")
    val slave = params("slave")


    val result = new scala.collection.mutable.ArrayBuffer[Map[String, AnyRef]]()

    val extraParams2 = params.filter(f => !f._2.isEmpty).filterNot{f=>
      Set("appName","version","slave").contains(f._1)
    }.map {
      f =>
        s"${f._1}=${encode(f._2)}"
    }.mkString("&")

    val userB = if (user == "-") "" else s"user=${user}"

    logger.info(s"write app extra {}", s"${masterUrl}/app/put/extra?${authTokenStr}${extraParams2}")
    val res = putAPPExtra(appName,params.filter(f => !f._2.isEmpty).filterNot{f=>
      Set("appName","version","slave").contains(f._1)
    })


    result += Map("name" -> s"write app extra", "rs" -> res)


    val configUrl = s"${masterUrl}/app/config"
    logger.info("install config {}", configUrl + s"?${authTokenStr}${userB}&appName=${appName}&installPath=${applicationDir}&slaves=${slave}&appVersion=${version}&${extraParams2}")

    val rps2 = httpClient.get(new Url(configUrl + s"?${authTokenStr}${userB}").
      addParam("appName", encode(appName)).
      addParam("installPath", encode(applicationDir)).
      addParam("slaves", encode(slave)).
      addParam("appVersion", encode(version)).
      query(s"${extraParams2}"))

    parseAppConfig(rps2.getContent).foreach{f=>
      result += Map("name" -> s"generate config ${f._1}", "rs" -> f._2)
    }

    result
  }
}
